package com.lfl.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @program: JavaEE-EFD
 * @description: md5工具类
 * @author: fengjd
 * @create: 2022-07-28 13:16
 **/
public class MD5Util {

    static char hexChars[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

    /**
     * 将str转换成32位md5的串
     *
     * @param str
     * @return
     */
    public static String convert32(String str) {
        if (str == null || str.length() == 0) {
            return "";
        }

        try {
            /* dm构造器初始化, 设置str的字节数组, */
            byte[] bytes = str.getBytes();
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(bytes);
            byte[] digest = md5.digest();
            int j = digest.length;
            char[] chars = new char[j * 2];
            int k = 0;
            for (int i = 0; i < digest.length; i++) {
                byte b = digest[i];
                /* 2^4 =16 给数字扩大16 */
                chars[k++] = hexChars[b >>> 4 & 0xf];
                chars[k++] = hexChars[b & 0xf];
            }
            return new String(chars);
        } catch (NoSuchAlgorithmException e) {
            return null;
        }
    }

    public String convert(String s) {
        return convert32(s).substring(8, 24);
    }
}
